package com.thfw.test.view.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.thfw.wmd.R;
import com.thfw.test.utils.BleUtil;
import com.thfw.test.utils.BluetoothDeviceManager;
import com.vise.xsnow.permission.OnPermissionCallback;
import com.vise.xsnow.permission.PermissionManager;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import scooper.cn.sc_base.AppActivities;


public class SplashActivity extends BaseActivity {

    private static final String TAG = SplashActivity.class.getCanonicalName();
    private HandlerThread handlerThread;
    private Handler startHandler;
    private long startTime;
    private static final int START_HANDLER_WHAT_LOGIN = 10;

    @Override
    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initView() {
        easyPermission();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startLoginThread();
        BluetoothDeviceManager.getInstance().init(this);

        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (SplashActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    SplashActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                }
            }
        }

    }

    private void startLoginThread() {
        new Thread(() -> {
            startTime = System.currentTimeMillis();
            if (handlerThread == null) {
                handlerThread = new HandlerThread(TAG + ".handleStartActivityThread");
            }
            if (!handlerThread.isAlive()) {
                handlerThread.start();
            }
            startHandler = new Handler(handlerThread.getLooper(), msg -> {
                //打开页面
                long endTime = System.currentTimeMillis();
                long sleepTime = 1000 - (endTime - startTime);
                if (sleepTime > 0) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                finish();
                AppActivities.instance().finishTo(SplashActivity.this, LoginActivity.class);
                return true;
            });

            //
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        checkBluetoothPermission();
        if(startHandler!=null){
            startHandler.sendEmptyMessage(START_HANDLER_WHAT_LOGIN);
        }
    }



    /**
     * 检查蓝牙权限
     */
    private void checkBluetoothPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                PermissionManager.instance().with(this).request(new OnPermissionCallback() {
                    @Override
                    public void onRequestAllow(String permissionName) {
                        enableBluetooth();
                    }

                    @Override
                    public void onRequestRefuse(String permissionName) {
                        finish();
                    }

                    @Override
                    public void onRequestNoAsk(String permissionName) {
                        finish();
                    }
                }, Manifest.permission.ACCESS_COARSE_LOCATION);
            } else {
                enableBluetooth();
            }
        } else {
            enableBluetooth();
        }
    }


    private void enableBluetooth() {
        if (!BleUtil.isBleEnable(this)) {
            startHandler.sendEmptyMessage(START_HANDLER_WHAT_LOGIN);
            BleUtil.enableBluetooth(this, 1);
        } else {
            boolean isSupport = BleUtil.isSupportBle(this);
            boolean isOpenBle = BleUtil.isBleEnable(this);
            startHandler.sendEmptyMessage(START_HANDLER_WHAT_LOGIN);
            invalidateOptionsMenu();
//            updateConnectedDevice();
        }
    }


    private void easyPermission() {
        Log.e(TAG, "easyPermission: " );
        String[] mPermissions = new String[]{
                 Manifest.permission.READ_CONTACTS
                , Manifest.permission.ACCESS_FINE_LOCATION
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                ,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
                , Manifest.permission.BLUETOOTH
                , Manifest.permission.BLUETOOTH_ADMIN
                , Manifest.permission.CHANGE_NETWORK_STATE
                , Manifest.permission.CHANGE_WIFI_STATE
                , Manifest.permission.ACCESS_NETWORK_STATE
                , Manifest.permission.READ_PHONE_STATE
                , Manifest.permission.RECORD_AUDIO};

        if (EasyPermissions.hasPermissions(this, mPermissions)) {
            // Already have permission, do the thing
            //startHandler.sendEmptyMessage(START_HANDLER_WHAT_LOGIN);
            return;
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "请给予权限,否则app无法正常运行",
                    AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE, mPermissions);
        }
    }
}
